package com.lc.test.controller;

import com.aspose.words.DocumentBuilder;
import com.aspose.words.ImageSaveOptions;
import com.aspose.words.SaveFormat;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.ImageType;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/word")
public class WordController {


    private final String path = "F:\\酒店场地使用协议书-最终版12.20.docx";

    private final String testPath = "F:\\test.docx";

    private final String outPath = "F:\\酒店场地使用协议书.docx";

    private final String outImgPath = "F:\\酒店场地使用协议书.png";

    private final String name = "E:\\酒店场地使用协议书";

    private final String testName = "E:\\酒店场地使用协议书";

    private final String key = "place";
    private final String value = "某某某宴会厅";

    @GetMapping("/fillWord")
    public void fillWord() {
        try {
            // 准备工作，生成docx对象
            InputStream is = Files.newInputStream(Paths.get(path));
            XWPFDocument docx = new XWPFDocument(is);
            List<XWPFParagraph> paragraphList = docx.getParagraphs();
            for (XWPFParagraph paragraph : paragraphList) {
                List<XWPFRun> runs = paragraph.getRuns();
                for (XWPFRun run : runs) {
                    if(key.equals(run.toString())){
                        run.setText(value, 0);
                    }
                }
            }
            OutputStream outputStream = Files.newOutputStream(Paths.get(outPath));
            docx.write(outputStream);
            Document document = new Document();
            document.loadFromStream(Files.newInputStream(Paths.get(outPath)), FileFormat.Auto);
            for (int i =0; i < document.getPageCount(); i++) {
                BufferedImage image = document.saveToImages(i, ImageType.Bitmap);
                File file = new File(name + (i + 1) + ".png");
                ImageIO.write(image, "PNG", file);
            }
            is.close();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @GetMapping("/toImg")
    public void toImg(){
        try {
            Document document = new Document(path);
            BufferedImage image = document.saveToImages( 0, ImageType.Bitmap);
            File file = new File(testName + System.currentTimeMillis() + ".png");
            ImageIO.write(image, "PNG", file);
            // 将Word转为PDF
            document.saveToFile(name + "Word转PDF.pdf", FileFormat.PDF);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/aspose")
    public void aspose(){
        try {
            isWordLicense();
            com.aspose.words.Document document = new com.aspose.words.Document(path);
            ImageSaveOptions options = new ImageSaveOptions(SaveFormat.PNG);
            options.setPrettyFormat(true);
            options.setUseAntiAliasing(true);
            options.setUseHighQualityRendering(true);
            options.setResolution(200F);
            List<BufferedImage> imageList = new ArrayList<>();
            for (int i = 0; i < document.getPageCount(); i++) {
                OutputStream output = new ByteArrayOutputStream();
                options.setPageIndex(i);
                document.save(output, options);
                ImageInputStream imageInputStream = ImageIO.createImageInputStream(parse(output));
                imageList.add(ImageIO.read(imageInputStream));
            }
            BufferedImage bufferedImage = mergeImage(false, imageList);
            ImageIO.write(bufferedImage, "png", new File(outImgPath));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private boolean isWordLicense() {
        boolean result = false;
        try {
            String s = "<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>20991231</LicenseExpiry><SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature></License>";
            ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes());
            com.aspose.words.License license = new com.aspose.words.License();
            license.setLicense(inputStream);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    private ByteArrayInputStream parse(OutputStream out) throws Exception {
        ByteArrayOutputStream arrayOutputStream = (ByteArrayOutputStream) out;
        return new ByteArrayInputStream(arrayOutputStream.toByteArray());
    }


    public static BufferedImage mergeImage(boolean isHorizontal, List<BufferedImage> imgs) throws IOException {
        // 生成新图片
        BufferedImage destImage = null;
        // 计算新图片的长和高
        int allw = 0, allh = 0, allwMax = 0, allhMax = 0;
        // 获取总长、总宽、最长、最宽
        for (int i = 0; i < imgs.size(); i++) {
            BufferedImage img = imgs.get(i);
            allw += img.getWidth();
            if (imgs.size() != i + 1) {
                allh += img.getHeight() + 5;
            } else {
                allh += img.getHeight();
            }
            if (img.getWidth() > allwMax) {
                allwMax = img.getWidth();
            }
            if (img.getHeight() > allhMax) {
                allhMax = img.getHeight();
            }
        }
        // 创建新图片
        if (isHorizontal) {
            destImage = new BufferedImage(allw, allhMax, BufferedImage.TYPE_INT_RGB);
        } else {
            destImage = new BufferedImage(allwMax, allh, BufferedImage.TYPE_INT_RGB);
        }
        Graphics2D g2 = (Graphics2D) destImage.getGraphics();
        g2.setBackground(Color.LIGHT_GRAY);
        g2.clearRect(0, 0, allw, allh);
        g2.setPaint(Color.RED);

        // 合并所有子图片到新图片
        int wx = 0, wy = 0;
        for (int i = 0; i < imgs.size(); i++) {
            BufferedImage img = imgs.get(i);
            int w1 = img.getWidth();
            int h1 = img.getHeight();
            // 从图片中读取RGB
            int[] ImageArrayOne = new int[w1 * h1];
            ImageArrayOne = img.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 逐行扫描图像中各个像素的RGB到数组中
            if (isHorizontal) { // 水平方向合并
                destImage.setRGB(wx, 0, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
            } else { // 垂直方向合并
                destImage.setRGB(0, wy, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
            }
            wx += w1;
            wy += h1 + 5;
        }


        return destImage;
    }

}
